import type { ECharts } from '../../../../../../../types/interfaces'
import type { UserAnalytics } from '../index'
import type {
  UserAnalyticsActivity,
  UserAnalyticsActivityType,
  UserAnalyticsCollectedData,
  UserAnalyticsCommentData,
  UserAnalyticsCommentStatus,
  UserAnalyticsData,
  UserAnalyticsPostRatingType,
  UserAnalyticsScriptData,
  UserAnalyticsScriptListType,
} from '../types'
import { BarChart } from '../../../../../../../components/bar_chart'
import { LineChart } from '../../../../../../../components/line_chart'
import { PieChart } from '../../../../../../../components/pie_chart'
import { ClickOutsideHandler } from '../../../../../../../lib/click_outside_handler'
import { ToolKit } from '../../../../../../../lib/utils/toolkit'
import {
  getChartLabelColor,
  logger,
  RATING_BACKGROUND_COLORS,
  WEEKDAYS_CHINESE,
} from '../../../../../../../types/constants'
import { SYMBOLS } from '../../../../../../../types/interfaces'
import { getInstallRangeColor } from '../types'

export class UserAnalyticsUI {
  // @Decorators.Identity
  readonly name: string = 'UserAnalyticsUI'
  // @Decorators.PublicState
  private static instance: UserAnalyticsUI
  // @Decorators.UIElement
  clickOutsideHandler: ClickOutsideHandler | null = null
  readonly DASHBOARD_ID: string = 'user-analytics-dashboard'
  // 留言前缀
  private get commentPrefix(): string {
    const { actualCommentPages, pageMaxCommentPages } = this.userAnalyticsInstance

    // 如果实际获取页数等于页面最大页数，说明获取了全部页面
    if (actualCommentPages >= pageMaxCommentPages) {
      return '所有'
    }

    // 如果只获取了部分页面，使用"最近"
    return '最近'
  }

  // @Decorators.TemporaryState
  isDashboardVisible: boolean = false
  charts: Map<string, ECharts> = new Map()

  constructor(private readonly userAnalyticsInstance: UserAnalytics) {
    this.userAnalyticsInstance = userAnalyticsInstance
  }

  /**
   * 获取单例实例
   */
  public static getInstance(userAnalyticsInstance: UserAnalytics): UserAnalyticsUI {
    if (!UserAnalyticsUI.instance) {
      UserAnalyticsUI.instance = new UserAnalyticsUI(userAnalyticsInstance)
    }
    return UserAnalyticsUI.instance
  }

  /**
   * 销毁看板
   */
  destroy(): void {
    this.removeDashboard()
    this.isDashboardVisible = false
    this.charts.clear()
  }

  /**
   * 切换看板显示状态
   */
  toggleDashboard(): void {
    this.isDashboardVisible ? this.hideDashboard() : this.showDashboard()
  }

  /**
   * 显示看板
   */
  showDashboard(): void {
    const $dashboard = $(`.${this.DASHBOARD_ID}`)

    if ($dashboard.length === 0) {
      this.renderDashboard()
    }
    else {
      $dashboard.show()
    }
    this.isDashboardVisible = true
  }

  /**
   * 隐藏看板
   */
  hideDashboard(): void {
    $(`.${this.DASHBOARD_ID}`).hide()

    this.isDashboardVisible = false
  }

  /**
   * 移除看板
   */
  removeDashboard(): void {
    $(`.${this.DASHBOARD_ID}`).remove()
  }

  /**
   * 渲染数据看板
   */
  renderDashboard(): void {
    this.userAnalyticsInstance.toggleButtonLoadingStatus(false)
    this.clickOutsideHandler = new ClickOutsideHandler({
      condition: () => $(`.${this.DASHBOARD_ID}`).is(':visible'),
      onOutsideClick: () => this.hideDashboard(),
      excludeSelectors: [`.${this.DASHBOARD_ID}`],
    })

    if (!this.userAnalyticsInstance.analyticsData)
      return

    this.removeDashboard() // 先清理旧看板

    const $dashboard = this.createDashboard(this.userAnalyticsInstance.userData!, this.userAnalyticsInstance.analyticsData)
    this.userAnalyticsInstance.tracker.creation($dashboard)

    $('body').append($dashboard)
    ToolKit.browser.platform.markProjectAlertElement($dashboard)

    this.renderSummaryCards($dashboard, this.userAnalyticsInstance.userData!, this.userAnalyticsInstance.analyticsData)
    this.renderRecentActivities($dashboard, this.userAnalyticsInstance.analyticsData)
    this.renderScriptStats($dashboard, this.userAnalyticsInstance.analyticsData)
    this.renderTimeDistribution($dashboard, this.userAnalyticsInstance.analyticsData)
    this.renderRatingDistribution($dashboard, this.userAnalyticsInstance.analyticsData)
    this.renderCommentStats($dashboard, this.userAnalyticsInstance.analyticsData)

    logger.info(`[${this.name}] 用户数据看板渲染完成`)
  }

  /**
   * 创建看板容器
   */
  private createDashboard(userData: UserAnalyticsCollectedData, analyticsData: UserAnalyticsData): JQuery<HTMLElement> {
    const { userInfo } = userData
    const { firstCreation, firstComment, commentRatingDistribution } = analyticsData

    const commentRatingEmpty = Object.values(commentRatingDistribution).every(value => value === 0)
    const hasComments = analyticsData.totalComments > 0
    const commentStatus = this.getCommentStatus(commentRatingEmpty, hasComments)

    // 计算活跃时间
    const activeTime = this.calculateActiveTime(firstCreation.createdDate, firstComment.timestamp)
    const activeTimeText = this.formatActiveTime(activeTime)

    // 获取留言统计信息
    const commentStatsDescription = this.getCommentStatsDescription()
    const commentLinkText = this.getCommentLinkText()

    return $(`
      <div class="${this.DASHBOARD_ID}">
        <div class="dashboard-header">
          <h3>${SYMBOLS.UI.CHART} 用户分析 - ${userInfo.name}<small>（${activeTimeText}）</small></h3>
          <div class="dashboard-controls">
            <button class="btn-close" title="关闭看板">${SYMBOLS.UI.CLOSE}</button>
          </div>
        </div>
        <div class="dashboard-content">
          <div class="summary-cards"></div>
          <div class="content-container">
            <div class="latest-section">
              <h4 title="显示用户最近一周内的活动记录">${SYMBOLS.UI.BELL} 最近活动</h4>
            </div>
            <div class="script-section">
              <h4 title="显示用户发布的脚本数据">${SYMBOLS.DOCUMENTS.SCROLL} 脚本信息</h4>
              <div class="charts-grid">
                <div id="total-install-distribution-chart" class="chart-item"></div>
                <div id="daily-install-distribution-chart" class="chart-item"></div>
              </div>
              <div class="charts-grid">
                <div id="script-rating-distribution-chart" class="chart-item"></div>
                <div id="creation-time-year-distribution-chart" class="chart-item"></div>
              </div>
              <div class="charts-grid">
                <div id="update-time-distribution-chart" class="chart-item"></div>
                <div id="update-hour-distribution-chart" class="chart-item"></div>
              </div>
            </div>
            <div class="comment-section">
              <h4 title="${commentStatsDescription}">${ToolKit.ui.element.generateLinkElement(`${commentLinkText}`, this.userAnalyticsInstance.discussionUrl)}</h4>
              <div class="comment-status">
                ${this.renderCommentStatus(commentStatus)}
              </div>
              <div class="charts-grid">
                <div id="comment-rating-distribution-chart" class="chart-item"></div>
              </div>
              <div class="charts-grid">
                <div id="comment-time-distribution-chart" class="chart-item"></div>
                <div id="comment-script-distribution-chart" class="chart-item"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    `).on('click', '.btn-close', () => this.hideDashboard())
  }

  /**
   * 获取评论状态信息
   */
  private getCommentStatus(commentRatingEmpty: boolean, hasComments: boolean): UserAnalyticsCommentStatus {
    if (!hasComments) {
      return {
        type: 'no-comments',
        message: '用户暂未发表任何留言',
        description: '该用户目前没有发帖或回复记录',
        className: 'comment-status-empty',
      }
    }

    if (commentRatingEmpty) {
      return {
        type: 'no-ratings',
        message: '用户未发表评价类型的留言',
        description: '该用户的留言均为无评价内容或技术讨论',
        className: 'comment-status-no-ratings',
      }
    }

    return {
      type: 'has-data',
      message: '留言数据分析',
      description: '包含评价分布、时间分布等统计信息',
      className: 'comment-status-has-data',
    }
  }

  /**
   * 渲染评论状态提示
   */
  private renderCommentStatus(status: UserAnalyticsCommentStatus): string {
    if (status.type === 'has-data')
      return '' // 有数据时不显示状态提示

    return `
    <div class="comment-status-item ${status.className}">
      <div class="comment-status-content">
        <div class="comment-status-title">${status.message}</div>
        <div class="comment-status-desc">${status.description}</div>
      </div>
    </div>
  `
  }

  /**
   * 计算活跃时间（取最早的活动时间）
   */
  private calculateActiveTime(firstCreationTime: number, firstCommentTime: number): {
    time: number
    type: 'script' | 'comment' | 'unknown'
    isAccurate: boolean
  } {
  // 如果两个时间都没有，返回未知
    if (!firstCreationTime && !firstCommentTime) {
      return {
        time: 0,
        type: 'unknown',
        isAccurate: false,
      }
    }

    // 只有脚本时间
    if (firstCreationTime && !firstCommentTime) {
      return {
        time: firstCreationTime,
        type: 'script',
        isAccurate: true,
      }
    }

    // 只有评论时间
    if (!firstCreationTime && firstCommentTime) {
      return {
        time: firstCommentTime,
        type: 'comment',
        isAccurate: true,
      }
    }

    // 两个时间都有，取较早的那个
    try {
      const creationDate = new Date(firstCreationTime).getTime()
      const commentDate = new Date(firstCommentTime).getTime()

      if (creationDate <= commentDate) {
        return {
          time: firstCreationTime,
          type: 'script',
          isAccurate: true,
        }
      }
      else {
        return {
          time: firstCommentTime,
          type: 'comment',
          isAccurate: true,
        }
      }
    }
    // eslint-disable-next-line unused-imports/no-unused-vars
    catch (error) {
      // 日期解析失败，返回任意一个有效的时间
      return {
        time: firstCreationTime || firstCommentTime,
        type: 'unknown',
        isAccurate: false,
      }
    }
  }

  /**
   * 格式化活跃时间显示
   */
  private formatActiveTime(options: { time: number, type: 'script' | 'comment' | 'unknown', isAccurate: boolean }): string {
    const { time, type, isAccurate } = options

    if (!time) {
      return '活跃时间未知'
    }

    try {
      const date = new Date(time)
      if (Number.isNaN(date.getTime())) {
        return '时间格式错误'
      }

      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const yearMonth = `${year}年${month}月`

      let prefix = ''
      let suffix = ''

      switch (type) {
        case 'script':
          prefix = ''
          suffix = '起活跃'
          break
        case 'comment':
          prefix = ''
          suffix = '起活跃'
          break
        case 'unknown':
          prefix = '约'
          suffix = '起活跃'
          break
      }

      if (!isAccurate) {
        prefix = `约${prefix}`
      }

      return `${prefix}${yearMonth}${suffix}`
    }
    // eslint-disable-next-line unused-imports/no-unused-vars
    catch (error) {
      return '时间解析失败'
    }
  }

  /**
   * 渲染摘要卡片
   */
  private renderSummaryCards($dashboard: JQuery<HTMLElement>, userData: UserAnalyticsCollectedData, analyticsData: UserAnalyticsData): void {
    const { scripts = [] } = userData
    const {
      totalScripts,
      allTotalInstalls,
      allDailyInstalls,
      firstCreation,
      lastUpdate,
      firstComment,
      lastComment,
      daysSinceLastScriptUpdate,
      daysSinceLastComment,
      totalComments,
      totalAnswererComments,
      totalCommentScript,
      totalPostScript,
      commentScriptGoodRating,
      commentScriptBadRating,
    } = analyticsData

    const firstCreationTime = firstCreation.createdDate || 0
    const latestUpdateTime = lastUpdate?.updatedDate || 0
    const firstCommentTime = firstComment?.timestamp || 0
    const lastCommentTime = lastComment?.timestamp || 0

    const totalScriptsCount = scripts.length
    const scriptUpdateStatus = this.getUpdateStatus(daysSinceLastScriptUpdate)
    const commentUpdateStatus = this.getUpdateStatus(daysSinceLastComment)
    const creationDuration = firstCreationTime && latestUpdateTime
      ? ToolKit.time.calculateDurationDays(firstCreationTime, latestUpdateTime)
      : 0
    const creationDurationText = ToolKit.time.formatTimeInterval(creationDuration, 'days')
    const commentDuration = firstCommentTime && lastCommentTime
      ? ToolKit.time.calculateDurationDays(firstCommentTime, lastCommentTime)
      : 0

    const $summaryContainer = $dashboard.find('.summary-cards')

    $summaryContainer.html(`
      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.TIME.CLOCK}</div>
        <div class="card-content">
          <div class="card-value" title="${ToolKit.time.formatDateTime(firstCreationTime)} 至 ${ToolKit.time.formatDateTime(latestUpdateTime)}">${creationDurationText}</div>
          <div class="card-label" title="从用户创建第一个脚本到最新更新脚本的时间间隔（单位：天）">创作周期</div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.DOCUMENTS.SCROLL}</div>
        <div class="card-content">
          <div class="card-value">${totalScripts}</div>
          <div class="card-label" title="用户脚本总个数">脚本数量</div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.UI.DOWNLOAD}</div>
        <div class="card-content">
          <div class="card-value">${allTotalInstalls.toLocaleString()}</div>
          <div class="card-label" title="用户所有脚本的总安装量总和">累计总安装量</div>
        </div>
      </div>

      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.UI.TREND_UP}</div>
        <div class="card-content">
          <div class="card-value">${allDailyInstalls.toLocaleString()}</div>
          <div class="card-label" title="用户所有脚本的日安装量总和">累计日安装量</div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.TIME.CLOCK}</div>
        <div class="card-content">
          <div class="card-value" title="${ToolKit.time.formatDateTime(firstCommentTime)} 至 ${ToolKit.time.formatDateTime(lastCommentTime)}">${ToolKit.time.formatTimeInterval(commentDuration, 'days')}</div>
          <div class="card-label" title="从用户${this.commentPrefix}留言中首次评论到最新评论的时间间隔（单位：天）">评论周期</div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.OTHERS.COMMENT}</div>
        <div class="card-content">
          <div class="card-value">${totalComments}</div>
          <div class="card-label" title="用户${this.commentPrefix}留言总次数：发帖数（完整）+ 回复数（部分）。无法统计用户非发帖人且非最新回复者的留言">留言次数</div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.OTHERS.LIKE}</div>
        <div class="card-content">
          <div class="card-value">${commentScriptGoodRating}<small>/${totalPostScript}</small></div>
          <div class="card-label" title="用户${this.commentPrefix}好评发帖的脚本总数/用户发帖的脚本总数">好评脚本数</div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="card-icon">${SYMBOLS.OTHERS.DISLIKE}</div>
        <div class="card-content">
          <div class="card-value">${commentScriptBadRating}<small>/${totalPostScript}</small></div>
          <div class="card-label" title="用户${this.commentPrefix}差评发帖的脚本总数/用户发帖的脚本总数">差评脚本数</div>
        </div>
      </div>
      
      <div class="summary-card overview-card">
        <div class="user-overview">
          <div class="user-avatar">
            <img src="${userData.userInfo.profileUrl}" alt="${userData.userInfo.name}" onerror="this.style.display='none'">
          </div>
          <div class="user-info">
            <div class="user-stats">
              <span class="stat">【脚本】一共发布${totalScriptsCount}个脚本${scriptUpdateStatus}</span>
              <span class="stat">【${this.commentPrefix}留言】${totalComments - totalAnswererComments} 次发帖，${totalAnswererComments} 次回复，涉及${totalCommentScript}个脚本${commentUpdateStatus}</span>
            </div>
            <div class="first-timeline">
              <ul>
                ${this.renderUserFirstTimeLine()}
              </ul>
            </div>
          </div>
        </div>
      </div>
    `)
  }

  /**
   * 渲染用户第一次活动时间线（按时间顺序）
   */
  private renderUserFirstTimeLine(): string {
    const { firstCreation, firstOriComment, firstAnswererComment } = this.userAnalyticsInstance.analyticsData!

    // 收集所有时间点
    const timelineEvents = [
      {
        type: 'script-creation',
        time: firstCreation.createdDate,
        content: this.getFirstScriptHtml(firstCreation),
        isValid: firstCreation.createdDate > 0,
      },
      {
        type: 'first-post',
        time: firstOriComment?.timestamp || 0,
        content: this.getFirstPostHtml(firstOriComment),
        isValid: firstOriComment?.timestamp > 0,
      },
      {
        type: 'first-reply',
        time: firstAnswererComment?.timestamp || 0,
        content: this.getFirstReplyHtml(firstAnswererComment),
        isValid: firstAnswererComment?.timestamp > 0,
      },
    ]

    // 过滤有效事件并按时间排序（从早到晚）
    const sortedEvents = timelineEvents
      .filter(event => event.isValid)
      .sort((a, b) => a.time - b.time)

    if (sortedEvents.length === 0) {
      return '<li>暂无活动记录</li>'
    }

    // 生成时间线 HTML
    return sortedEvents.map(event => event.content).join('')
  }

  /**
   * 获取第一次发布脚本的 HTML
   */
  private getFirstScriptHtml(creation: { createdDate: number, name: string, url: string }): string {
    if (!creation.createdDate)
      return ''

    const formattedTime = ToolKit.time.formatYearMonth(creation.createdDate)
    return `
    <li>
      ${formattedTime} 第一次发布：${ToolKit.ui.element.generateLinkElement(
        `${SYMBOLS.DOCUMENTS.SCROLL} ${ToolKit.string.truncate(creation.name, 30)}`,
        creation.url,
      )}
    </li>
  `
  }

  /**
   * 获取第一次发帖的 HTML
   */
  private getFirstPostHtml(comment: UserAnalyticsCommentData | undefined): string {
    if (!comment || !comment.timestamp)
      return ''

    const formattedTime = ToolKit.time.formatYearMonth(comment.timestamp)
    return `
    <li>
      ${formattedTime} 第一次发帖：${ToolKit.ui.element.generateLinkElement(
        `【${ToolKit.string.truncate(comment.scriptName, 30)}】${comment.content}`,
        comment.url,
      )}
    </li>
  `
  }

  /**
   * 获取第一次回复的 HTML
   */
  private getFirstReplyHtml(comment: UserAnalyticsCommentData | undefined): string {
    if (!comment || !comment.timestamp)
      return ''

    const formattedTime = ToolKit.time.formatYearMonth(comment.timestamp)
    return `
    <li>
      ${formattedTime} 第一次回复：${ToolKit.ui.element.generateLinkElement(
        `【${ToolKit.string.truncate(comment.scriptName, 30)}】${comment.content}`,
        comment.url,
      )}
    </li>
  `
  }

  /**
   * 获取更新状态文本
   */
  private getUpdateStatus(daysSinceLastUpdate: number | undefined): string {
    if (daysSinceLastUpdate === undefined) {
      return '（未知更新时间）'
    }
    else if (daysSinceLastUpdate === 0) {
      return '（今天有更新）'
    }
    else if (daysSinceLastUpdate < 7) {
      return `（${daysSinceLastUpdate}天前更新）`
    }
    else if (daysSinceLastUpdate < 30) {
      const weeks = Math.floor(daysSinceLastUpdate / 7)
      return `（${weeks}周前更新）`
    }
    else if (daysSinceLastUpdate < 365) {
      const months = Math.floor(daysSinceLastUpdate / 30)
      return `（${months}月前更新）`
    }
    else {
      const years = Math.floor(daysSinceLastUpdate / 365)
      return `（${years}年前更新）`
    }
  }

  /**
   * 渲染最近活动
   */
  private renderRecentActivities($dashboard: JQuery<HTMLElement>, analyticsData: UserAnalyticsData): void {
    const { recentActivities = [] } = analyticsData
    const $latestSection = $dashboard.find('.latest-section')

    $latestSection.append(`
    <div class="recent-activities">
      <div class="activity-timeline">
        ${this.renderActivityTimeline(recentActivities)}
      </div>
    </div>
  `)
  }

  /**
   * 渲染活动时间线
   */
  private renderActivityTimeline(activities: UserAnalyticsActivity[]): string {
    const oneWeekAgo = Date.now() - (7 * 24 * 60 * 60 * 1000)
    const recentActivities = activities
      .filter(activity => activity.timestamp >= oneWeekAgo)
      .sort((a, b) => b.timestamp - a.timestamp)
      .slice(0, 10) // 最多显示10条

    if (recentActivities.length === 0) {
      return `
      <div class="no-recent-activities">
        <div class="empty-state">
          <p>最近一周暂无活动</p>
        </div>
      </div>
    `
    }

    return `
    <div class="activity-list">
      ${recentActivities.map(activity => this.renderActivityItem(activity)).join('')}
    </div>
  `
  }

  /**
   * 渲染单个活动项
   */
  private renderActivityItem(activity: UserAnalyticsActivity): string {
    const timeAgo = ToolKit.time.formatRelativeTime(activity.timestamp)
    const icon = this.getActivityIcon(activity.type)
    const content = this.getActivityContent(activity)

    return `
    <div class="activity-item" data-activity-type="${activity.type}" data-timestamp="${activity.timestamp}">
      <div class="activity-icon">${icon}</div>
      <div class="activity-content">
        <div class="activity-text">${content}</div>
        <div class="activity-time">${timeAgo}</div>
      </div>
    </div>
  `
  }

  /**
   * 获取活动图标
   */
  private getActivityIcon(activityType: UserAnalyticsActivityType): string {
    const icons = {
      'script-created': SYMBOLS.DOCUMENTS.SCROLL,
      'script-updated': SYMBOLS.UI.EDIT,
      'post-created': SYMBOLS.OTHERS.COMMENT,
      'reply-created': SYMBOLS.ARROWS.BACK,
    }

    return icons[activityType] || SYMBOLS.UI.FOOTPRINT
  }

  /**
   * 获取活动内容
   */
  private getActivityContent(activity: UserAnalyticsActivity): string {
    switch (activity.type) {
      case 'script-created':
        return `创建了脚本 <a href="${activity.scriptUrl}" target="_blank">【${ToolKit.string.truncate(activity.scriptName, 25)}】</a>`

      case 'script-updated':
        return `更新了脚本 <a href="${activity.scriptUrl}" target="_blank">【${ToolKit.string.truncate(activity.scriptName, 25)}】</a>`

      case 'post-created':
        return `在 <a href="${activity.scriptUrl}" target="_blank">【${ToolKit.string.truncate(activity.scriptName, 25)}】</a> 发表了帖子：<a href="${activity.commentUrl}" target="_blank">${ToolKit.string.truncate(activity.content || '', 30)}</a>`

      case 'reply-created':
        return `回复了 <a href="${activity.scriptUrl}" target="_blank">【${ToolKit.string.truncate(activity.scriptName, 25)}】</a> 的帖子：${this.getRatingIcon(activity.rating || 'none')}<a href="${activity.commentUrl}" target="_blank">${ToolKit.string.truncate(activity.content || '', 30)}</a>`

      default:
        return '进行了未知操作'
    }
  }

  /**
   * 获取评价图标
   */
  private getRatingIcon(rating: UserAnalyticsPostRatingType): string {
    const icons: Record<UserAnalyticsPostRatingType, string> = {
      good: SYMBOLS.OTHERS.DISLIKE,
      ok: SYMBOLS.OTHERS.NEUTRAL,
      bad: SYMBOLS.OTHERS.DISLIKE,
      none: '',
    }

    return icons[rating] || ''
  }

  /**
   * 渲染脚本统计
   */
  private renderScriptStats($dashboard: JQuery<HTMLElement>, analyticsData: UserAnalyticsData): void {
    const {
      scriptTotalInstallRanges,
      scriptDailyInstallRanges,
      topRatedScripts,
      topBadRatedScripts,
      mostRatedScripts,
      topDailyInstalls,
      topTotalInstalls,
    } = analyticsData

    const $scriptSection = $dashboard.find('.script-section h4')

    // 添加脚本排行榜区域
    $scriptSection.after(`
    <div class="script-rankings">
      <div class="ranking-group">
        <h5>评价排行榜</h5>
        <div class="ranking-list" id="script-rating-rankings"></div>
      </div>
      <div class="ranking-group">
        <h5>安装量排行榜</h5>
        <div class="ranking-list" id="script-install-rankings"></div>
      </div>
      <div class="ranking-group">
        <h5>特殊统计</h5>
        <div class="ranking-list" id="script-special-rankings"></div>
      </div>
    </div>
  `)

    // 渲染评价排行榜
    this.renderRatingRankings($dashboard, {
      topRatedScripts,
      topBadRatedScripts,
      mostRatedScripts,
    })

    // 渲染安装量排行榜
    this.renderInstallRankings($dashboard, {
      topDailyInstalls,
      topTotalInstalls,
    })

    // 渲染特殊统计
    this.renderSpecialScripts($dashboard, analyticsData)

    // 总安装量分布饼图
    const totalInstallChart = new BarChart({
      id: 'total-install-distribution-chart',
      title: '总安装量分布',
      categories: Object.keys(scriptTotalInstallRanges),
      values: Object.values(scriptTotalInstallRanges),
      seriesOptions: {
        itemStyle: {
          color: (params: any) => {
            return getInstallRangeColor(params.name, 'total')
          },
        },
      },
    })

    // 日安装量分布饼图
    const dailyInstallChart = new BarChart({
      id: 'daily-install-distribution-chart',
      title: '日安装量分布',
      categories: Object.keys(scriptDailyInstallRanges),
      values: Object.values(scriptDailyInstallRanges),
      seriesOptions: {
        itemStyle: {
          color: (params: any) => {
            return getInstallRangeColor(params.name, 'daily')
          },
        },
      },
    })

    this.renderChart($dashboard, totalInstallChart, 'total-install-distribution-chart')
    this.renderChart($dashboard, dailyInstallChart, 'daily-install-distribution-chart')
  }

  /**
   * 渲染评价排行榜
   */
  private renderRatingRankings($dashboard: JQuery<HTMLElement>, rankings: {
    topRatedScripts: UserAnalyticsScriptData[]
    topBadRatedScripts: UserAnalyticsScriptData[]
    mostRatedScripts: UserAnalyticsScriptData[]
  }): void {
    const $container = $dashboard.find('#script-rating-rankings')

    const html = `
    <div class="ranking-category">
      <h6>${SYMBOLS.UI.STAR} 评价最多</h6>
      ${this.renderScriptList(rankings.mostRatedScripts, 'totalRatings', 3)}
    </div>
    <div class="ranking-category">
      <h6>${SYMBOLS.OTHERS.LIKE} 好评最多</h6>
      ${this.renderScriptList(rankings.topRatedScripts, 'good', 3)}
    </div>
    <div class="ranking-category">
      <h6>${SYMBOLS.OTHERS.DISLIKE} 差评最多</h6>
      ${this.renderScriptList(rankings.topBadRatedScripts, 'bad', 3)}
    </div>
  `

    $container.html(html)
    this.bindScriptClickEvents($container)
  }

  /**
   * 渲染安装量排行榜
   */
  private renderInstallRankings($dashboard: JQuery<HTMLElement>, rankings: {
    topDailyInstalls: UserAnalyticsScriptData[]
    topTotalInstalls: UserAnalyticsScriptData[]
  }): void {
    const $container = $dashboard.find('#script-install-rankings')

    const html = `
    <div class="ranking-category">
      <h6>${SYMBOLS.UI.DOWNLOAD} 总安装量TOP3</h6>
      ${this.renderScriptList(rankings.topTotalInstalls, 'totalInstalls', 3)}
    </div>
    <div class="ranking-category">
      <h6>${SYMBOLS.UI.TREND_UP} 日安装量TOP3</h6>
      ${this.renderScriptList(rankings.topDailyInstalls, 'dailyInstalls', 3)}
    </div>
  `
    $container.html(html)
    this.bindScriptClickEvents($container)
  }

  /**
   * 渲染特殊脚本统计
   */
  private renderSpecialScripts($dashboard: JQuery<HTMLElement>, analyticsData: UserAnalyticsData): void {
    const { zeroBadRatingScripts, zeroInstallScripts, unratedScripts, totalScripts } = analyticsData
    const $container = $dashboard.find('#script-special-rankings')

    const html = `
     <div class="ranking-category">
      <h6>${SYMBOLS.UI.ZERO} 零差评脚本（${zeroBadRatingScripts.length}/${totalScripts}）</h6>
      ${this.renderScriptList(zeroBadRatingScripts, 'zeroBadRating', 5)}
    </div>
    <div class="ranking-category">
      <h6>${SYMBOLS.UI.ZERO} 零安装脚本（${zeroInstallScripts.length}/${totalScripts}）</h6>
      ${this.renderScriptList(zeroInstallScripts, 'zeroInstall', 5)}
    </div>
    <div class="ranking-category">
      <h6>${SYMBOLS.UI.STAR} 无评价脚本（${unratedScripts.length}/${totalScripts}）</h6>
      ${this.renderScriptList(unratedScripts, 'unrated', 5)}
    </div>
  `

    $container.html(html)
    this.bindScriptClickEvents($container)
  }

  /**
   * 渲染脚本列表
   */
  private renderScriptList(scripts: UserAnalyticsScriptData[], type: UserAnalyticsScriptListType, limit: number = 5): string {
    if (scripts.length === 0) {
      return '<div class="no-data">暂无数据</div>'
    }

    const displayedScripts = scripts
      .sort((a, b) => {
        if (b.totalInstalls !== a.totalInstalls && ['totalInstalls', 'dailyInstalls', 'zeroBadRating'].includes(type))
          return b.totalInstalls - a.totalInstalls

        if (b.totalRatings !== a.totalRatings && ['totalRatings'].includes(type))
          return b.totalRatings - a.totalRatings

        if (b.ratings.good !== a.ratings.good && ['good'].includes(type))
          return b.ratings.good - a.ratings.good

        if (b.ratings.bad !== a.ratings.bad && ['bad'].includes(type))
          return b.ratings.bad - a.ratings.bad

        return b.updatedDate - a.updatedDate
      })
      .slice(0, limit)

    return `
    <ul class="script-list">
      ${displayedScripts.map((script, index) => this.renderScriptListItem(script, index + 1, type)).join('')}
      ${scripts.length > limit ? `<li class="more-item">... 还有 ${scripts.length - limit} 个</li>` : ''}
    </ul>
  `
  }

  /**
   * 渲染单个脚本列表项
   */
  private renderScriptListItem(script: UserAnalyticsScriptData, rank: number, type: UserAnalyticsScriptListType): string {
    const rankIcon = this.getRankIcon(rank)
    const value = this.getScriptValue(script, type)

    return `
    <li class="script-item" data-script-id="${script.id}" data-script-url="${script.url}">
      <span class="rank">${rankIcon}</span>
      <a href="${script.url}" class="script-name" target="_blank" title="点击查看脚本详情">
        ${ToolKit.string.truncate(script.name, 25)}
      </a>
      <span class="script-value">${value}</span>
    </li>
  `
  }

  /**
   * 获取排名图标
   */
  private getRankIcon(rank: number): string {
    const icons = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟']
    return rank <= icons.length ? icons[rank - 1] : `${rank}.`
  }

  /**
   * 获取脚本的统计值
   */
  private getScriptValue(script: UserAnalyticsScriptData, type: UserAnalyticsScriptListType): number {
    switch (type) {
      case 'good':
        return script.ratings.good
      case 'bad':
        return script.ratings.bad
      case 'totalRatings':
        return script.totalRatings
      case 'totalInstalls':
        return script.totalInstalls
      case 'dailyInstalls':
        return script.dailyInstalls
      case 'zeroBadRating':
        return script.totalInstalls
      case 'zeroInstall':
        return script.totalInstalls
      case 'unrated':
        return script.ratings.good + script.ratings.ok + script.ratings.bad
      default:
        return 0
    }
  }

  /**
   * 绑定脚本点击事件
   */
  private bindScriptClickEvents($container: JQuery<HTMLElement>): void {
    $container.find('.script-item').on('click', function (e) {
      e.preventDefault()

      const $item = $(this)
      const scriptUrl = $item.data('script-url')
      const scriptName = $item.find('.script-name').text().trim()

      if (scriptUrl) {
        // 在新标签页打开脚本链接
        ToolKit.browser.url.openNewTab(scriptUrl)

        // 可选：添加点击反馈
        $item.addClass('clicked')
        setTimeout(() => $item.removeClass('clicked'), 200)

        logger.info(`[UserAnalyticsUI] 打开脚本: ${scriptName}`, { url: scriptUrl })
      }
    })
  }

  /**
   * 渲染时间分布
   */
  private renderTimeDistribution($dashboard: JQuery<HTMLElement>, analyticsData: UserAnalyticsData): void {
    const { creationTimeDistribution, updateTimeDistribution, updateHourDistribution } = analyticsData

    // 创建时间分布（年）
    const creationChartYear = new BarChart({
      id: 'creation-time-year-distribution-chart',
      title: '创建时间分布（年）',
      categories: Object.keys(creationTimeDistribution.byYear).sort(),
      values: Object.keys(creationTimeDistribution.byYear).sort().map(key => creationTimeDistribution.byYear[key]),
    })

    // 更新时间分布（星期）
    const updateChart = new BarChart({
      id: 'update-time-distribution-chart',
      title: '更新时间分布',
      categories: Object.keys(updateTimeDistribution),
      values: Object.values(updateTimeDistribution),
    })

    // 更新时间分布（24小时）
    const updateHourChart = new LineChart({
      id: 'update-hour-distribution-chart',
      title: '更新时间分布（24小时）',
      categories: Object.keys(updateHourDistribution).map(key => key.replace(':00', '').replace(/^0+(?=\d)/, '')),
      values: Object.values(updateHourDistribution),
      formatTooltipName: (name: string) => `${name}:00`,
    })

    this.renderChart($dashboard, creationChartYear, 'creation-time-year-distribution-chart')
    this.renderChart($dashboard, updateChart, 'update-time-distribution-chart')
    this.renderChart($dashboard, updateHourChart, 'update-hour-distribution-chart')
  }

  /**
   * 渲染评价分布
   */
  private renderRatingDistribution($dashboard: JQuery<HTMLElement>, analyticsData: UserAnalyticsData): void {
    const { scriptRatingDistribution, commentRatingDistribution } = analyticsData

    // 脚本评价分布
    const scriptRatingChart = new BarChart({
      id: 'script-rating-distribution-chart',
      title: '脚本评价分布',
      categories: ['好评', '一般', '差评'],
      values: [scriptRatingDistribution.good, scriptRatingDistribution.ok, scriptRatingDistribution.bad],
      seriesOptions: {
        itemStyle: {
          color: (params: any) => {
            const labelItem = Object.values(RATING_BACKGROUND_COLORS).find(item => item.name === params.name)
            return getChartLabelColor(labelItem?.color || '#5470C6', params.name)
          },
        },
      },
    })

    // 评论评价分布
    const commentRatingChart = new PieChart({
      id: 'comment-rating-distribution-chart',
      title: '留言类型分布',
      data: [
        { name: '好评', value: commentRatingDistribution.good },
        { name: '一般', value: commentRatingDistribution.ok },
        { name: '差评', value: commentRatingDistribution.bad },
        { name: '回复', value: commentRatingDistribution.none },
      ].filter(item => item.value > 0),
      seriesOptions: {
        itemStyle: {
          color: (params: any) => {
            const labelItem = Object.values(RATING_BACKGROUND_COLORS).find(item => item.name === params.name)
            return getChartLabelColor(labelItem?.color || '#5470C6', params.name)
          },
        },
      },
      renderEmpty: false,
    })

    this.renderChart($dashboard, scriptRatingChart, 'script-rating-distribution-chart')
    this.renderChart($dashboard, commentRatingChart, 'comment-rating-distribution-chart')
  }

  /**
   * 渲染评论统计
   */
  private renderCommentStats($dashboard: JQuery<HTMLElement>, analyticsData: UserAnalyticsData): void {
    const { commentTimeDistribution, commentScriptDistribution } = analyticsData

    // 评论时间分布
    const commentTimeChart = new BarChart({
      id: 'comment-time-distribution-chart',
      title: '评论时间分布',
      categories: WEEKDAYS_CHINESE,
      values: commentTimeDistribution.byWeekday,
    })

    // 评论按脚本分布
    const topThreshold = 3
    const topScripts = Object.entries(commentScriptDistribution)
      .sort(([_, a], [__, b]) => {
        const aCount = a.count
        const bCount = b.count

        // 评论数相同，按时间排序（越早越靠前）
        if (aCount === bCount) {
          return b.timestamp - a.timestamp
        }

        return bCount - aCount
      })
      .slice(0, topThreshold)

    const commentScriptChart = new BarChart({
      id: 'comment-script-distribution-chart',
      title: `脚本评论数（TOP${topThreshold}）`,
      categories: topScripts.map(([script]) => ToolKit.string.truncate(script, 15)),
      values: topScripts.map(([_, data]) => data.count),
      renderEmpty: false,
    })

    this.renderChart($dashboard, commentTimeChart, 'comment-time-distribution-chart')
    this.renderChart($dashboard, commentScriptChart, 'comment-script-distribution-chart')
  }

  /**
   * 渲染图表
   */
  private renderChart($dashboard: JQuery<HTMLElement>, chart: any, chartId: string): void {
    const $chartContainer = $dashboard.find(`#${chartId}`)

    if ($chartContainer.length === 0) {
      logger.warn(`[${this.name}] 图表容器不存在`, { chartId })
      return
    }

    const chartHtml = chart.render()
    $chartContainer.html(chartHtml)
    chart.bindEvents()

    // 存储图表实例
    this.charts.set(chartId, chart.getChartInstance())
  }

  /**
   * 获取留言统计描述
   */
  private getCommentStatsDescription(): string {
    const { actualCommentPages, pageMaxCommentPages } = this.userAnalyticsInstance

    // 获取了全部页面
    if (actualCommentPages >= pageMaxCommentPages) {
      return `显示用户所有留言统计，基于全部${pageMaxCommentPages}页的数据`
    }

    // 只获取了部分页面
    if (actualCommentPages === 1) {
      return `显示用户最近留言统计，基于第1页的数据，共${pageMaxCommentPages}页`
    }

    return `显示用户最近留言统计，基于前${actualCommentPages}页的数据，共${pageMaxCommentPages}页`
  }

  /**
   * 获取留言链接文本
   */
  private getCommentLinkText(): string {
    const { actualCommentPages, pageMaxCommentPages } = this.userAnalyticsInstance

    // 获取了全部页面
    if (actualCommentPages >= pageMaxCommentPages) {
      return `${SYMBOLS.OTHERS.COMMENT} 所有留言`
    }

    // 只获取了部分页面
    if (actualCommentPages === 1) {
      return `${SYMBOLS.OTHERS.COMMENT} 最近留言（第1页）`
    }

    return `${SYMBOLS.OTHERS.COMMENT} 最近留言（前${actualCommentPages}页）`
  }
}
